<?php
namespace App\Services\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

use App\Models\Role as RoleModels;

/**
 * 角色逻辑处理
 * Class RoleServices
 * @package App\Services\Admin
 */
class RoleServices extends \App\Services\ComService
{
    /**
     * 根据查询条件获取角色数据
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request){
        //搜索条件
        $searchData = $request->input('search');
        //每页显示数量
        $perPage = trim($request->input('perPage'));

        //构造where条件
        $whereCondition = [];
        if(isset($searchData['status']) && in_array($searchData['status'], [0,1])){
            $whereCondition[] = [
                'status', '=', $searchData['status']
            ];
        }
        !empty($searchData['name']) && !empty(trim($searchData['name'])) && $whereCondition[] = [
            'name', 'like', $searchData['name'] . '%'
        ];

        empty($perPage) && $perPage = 20;

        return RoleModels::where($whereCondition)->paginate($perPage);


    }

    /**
     * 编辑 或是保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveRole(Request $request){
        //编辑
        $id = $request->input('id');
        $name = $request->input('name');

        $roleObject = new RoleModels();
        if(!empty($id)){
            $roleObject = RoleModels::find($id);
            if(empty($roleObject)){
                return $this->responseError('不存在的角色');
            }

            if(1 == $roleObject->is_administrator){
                return $this->responseError('不能编辑超级管理员');
            }

            if($name != $roleObject->name){
                if(!empty(RoleModels::where('name', '=', $name)->first())){
                    return $this->responseError('角色名称已经存在');
                }
            }
        } else {
            if(!empty(RoleModels::where('name', '=', $name)->first())){
                return $this->responseError('角色名称已经存在');
            }
        }

        $roleObject->name = $name;
        $roleObject->status = $request->input('status');
        $roleObject->is_administrator = 0;

        try{
            $roleObject->save();

            return $this->responseSuccess('操作成功');
        } catch(\Exception $e){
            return $this->responseError($e->getMessage());
        }

    }

    /**
     * 更新超级管理员的规则
     * @return bool
     */
    public function resetAdministrator(){
        //菜单处理器
        $menuService = new MenuService();
        //规则模型
        $roleModel = new RoleModels();

        //查找超级用户
        $administratorObject = RoleModels::where('is_administrator', '=', 1)->first();
        if(empty($administratorObject)){
            $administratorObject = $roleModel;
        }

        $menuTreeData = $menuService->getAdministratorMenu();
        $administratorObject->rule = $menuTreeData;
        if(empty($administratorObject->id)){
            $administratorObject->name = '超级管理员';
            $administratorObject->status = 0;
            $administratorObject->is_administrator = 1;
        }

        try{
            $administratorObject->save();
            return true;
        } catch (\Exception $e){
            //
            return false;
        }
    }

    /**
     * 获取超级会员数据
     * @return mixed
     */
    public function getAdministrator(){
        return RoleModels::where('is_administrator', '=', 1)->first();
    }

    /**
     * 根据规则ID，返回对应规则数据
     * @param $id
     * @return mixed
     */
    public function getRoleObject($id){
        return RoleModels::find($id);
    }

    /**
     * 保存规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveRules(Request $request){
        if(!$request->isMethod('post')){
            return $this->responseError('错误的请求方式');
        }

        $roleObject = RoleModels::find($request->post('roleId'));
        $menuIds = $request->post('menuIds');

        if(empty($roleObject->id)){
            return $this->responseError('不存在的规则');
        }
        if(!isset($roleObject->is_administrator['value']) || 1 == $roleObject->is_administrator['value']){
            return $this->responseError('超级管理员不能修改规则');
        }

        //菜单处理
        $menuService = new MenuService();

        //选中的菜单
        $rules = [];
        if(!empty($menuIds) && is_array($menuIds)){
            $menuArr = $menuService->getMenuArrWhereIn($menuIds);

            foreach ($menuArr as $key=>$val){
                if(in_array($val['id'], $menuIds)){
                    $rules[$val['id']] = isset($val['url']['value']) && !empty($val['url']['value']) ? $val['url']['value'] : $val['id'];
                }
            }
        }

        $roleObject->rule = $rules;

        try{
            $roleObject->save();

            return $this->responseSuccess([], '操作成功');
        }catch (\Exception $e){
            $errorMsg = $e->getMessage() ? $e->getMessage() : '系统正在维护，请重新操作';
            return $this->responseError($errorMsg);
        }


    }

    /**
     * 获取管理员的数据
     * @return array
     */
    public function getRoleArr(){
        $roleObject = RoleModels::where('is_administrator', '=', 0)->get();
        return !empty($roleObject) ? $roleObject->toArray() : [];
    }
}
